import Mock from 'mockjs';

// 操作模块和操作项多样化
const moduleAndActionList = [
  { module: '服务管理', action: '开通服务' },
  { module: '用户管理', action: '新增用户' },
  { module: '日志管理', action: '导出日志' },
  { module: '权限管理', action: '分配权限' },
  { module: '系统设置', action: '修改配置' },
  { module: '消息中心', action: '发送通知' },
];

const loginLogList = Mock.mock({
  'list|100': [
    {
      'id|+1': 1,
      type: '登录日志',
      'userId|+1': 1,
      userName: '@cname',
      userMobile: '@integer(13000000000, 19999999999)', // 纯数字手机号
      userAvatar: function() {
        return Math.random() > 0.5 ? Mock.Random.image('36x36', '#b7e3ff', '#fff', 'png', 'A') : '';
      },
      address: '@province@city',
      ip: '@ip',
      createdAt: '@datetime',
    },
  ],
});

const optLogList = Mock.mock({
  'list|100': [
    {
      'id|+1': 1,
      type: '操作日志',
      'userId|+1': 1,
      userName: '@cname',
      userMobile: '@integer(13000000000, 19999999999)', // 纯数字手机号
      userAvatar: function() {
        return Math.random() > 0.5 ? Mock.Random.image('36x36', '#b7e3ff', '#fff', 'png', 'A') : '';
      },
      address: '@province@city',
      ip: '@ip',
      get operateModule() {
        const item = moduleAndActionList[Math.floor(Math.random() * moduleAndActionList.length)];
        return item.module;
      },
      get operate() {
        const item = moduleAndActionList[Math.floor(Math.random() * moduleAndActionList.length)];
        return item.action;
      },
      createdAt: '@datetime',
    },
  ],
});

const moduleList = moduleAndActionList.map(item => item.module);

// 定义登录日志项类型
interface LoginLogItem {
  id: number;
  type: string;
  userId: number;
  userName: string;
  userMobile: string;
  userAvatar: string;
  address: string;
  ip: string;
  operateModule: string;
  operate: string;
  createdAt: string;
}

// 登录日志-列表
Mock.mock('/api/log/getLoginLogListByPage', 'post', (options) => {
  const body = options.body instanceof FormData ? Object.fromEntries(options.body.entries()) : JSON.parse(options.body || '{}');
  const page = parseInt(body.page) || 1;
  const pageSize = parseInt(body.pageSize) || 10;
  let list = loginLogList.list;

  // 关键字过滤（昵称或手机号）
  if (body.keyword) {
    const keyword = body.keyword.trim();
    list = list.filter((item: any) =>
      (item.userName && item.userName.includes(keyword)) ||
      (item.userMobile && String(item.userMobile).includes(keyword))
    );
  }

  // 时间区间过滤
  if (body.startDate && body.endDate) {
    const start = new Date(body.startDate);
    const end = new Date(body.endDate);
    list = list.filter((item: any) => {
      const date = new Date(item.createdAt);
      return date >= start && date <= end;
    });
  }

  // 新增：排序逻辑
  if (body.orderBy) {
    try {
      const orderObj = typeof body.orderBy === 'string' ? JSON.parse(body.orderBy) : body.orderBy;
      if (orderObj.field && orderObj.order) {
        list = list.slice().sort((a: any, b: any) => {
          const aVal = (a as any)[orderObj.field];
          const bVal = (b as any)[orderObj.field];
          // 针对 createdAt 字段用时间戳比较
          if (orderObj.field === 'createdAt') {
            const aTime = new Date(aVal).getTime();
            const bTime = new Date(bVal).getTime();
            if (aTime === bTime) return 0;
            if (orderObj.order === 'ascend') {
              return aTime - bTime;
            } else {
              return bTime - aTime;
            }
          }
          // 其它字段按原逻辑
          if (aVal === bVal) return 0;
          if (orderObj.order === 'ascend') {
            return aVal > bVal ? 1 : -1;
          } else {
            return aVal < bVal ? 1 : -1;
          }
        });
      }
    } catch (error) {
      console.error('排序参数解析失败:', error);
    }
  }

  const total = list.length;
  const totalPage = Math.ceil(total / pageSize);
  const startIdx = (page - 1) * pageSize;
  const endIdx = Math.min(startIdx + pageSize, total);
  const pageList = list.slice(startIdx, endIdx);

  return {
    code: '100',
    message: '操作成功',
    data: {
      total,
      pageSize,
      totalPage,
      page,
      startIdx,
      endIdx,
      offset: startIdx,
      list: pageList,
    },
  };
});

// 操作日志-列表
Mock.mock('/api/log/getOptLogListByPage', 'post', (options) => {
  const body = options.body instanceof FormData ? Object.fromEntries(options.body.entries()) : JSON.parse(options.body || '{}');
  const page = parseInt(body.page) || 1;
  const pageSize = parseInt(body.pageSize) || 10;
  let list = optLogList.list;

  // 关键字过滤（昵称或手机号）
  if (body.keyword) {
    const keyword = body.keyword.trim();
    list = list.filter((item: any) =>
      (item.userName && item.userName.includes(keyword)) ||
      (item.userMobile && String(item.userMobile).includes(keyword))
    );
  }

  // 模块过滤
  if (body.module) {
    list = list.filter((item: any) => item.operateModule === body.module);
  }

  // 时间区间过滤
  if (body.startDate && body.endDate) {
    const start = new Date(body.startDate);
    const end = new Date(body.endDate);
    list = list.filter((item: any) => {
      const date = new Date(item.createdAt);
      return date >= start && date <= end;
    });
  }

  // 新增：排序逻辑
  if (body.orderBy) {
    try {
      const orderObj = typeof body.orderBy === 'string' ? JSON.parse(body.orderBy) : body.orderBy;
      if (orderObj.field && orderObj.order) {
        list = list.slice().sort((a: any, b: any) => {
          const aVal = (a as any)[orderObj.field];
          const bVal = (b as any)[orderObj.field];
          // 针对 createdAt 字段用时间戳比较
          if (orderObj.field === 'createdAt') {
            const aTime = new Date(aVal).getTime();
            const bTime = new Date(bVal).getTime();
            if (aTime === bTime) return 0;
            if (orderObj.order === 'ascend') {
              return aTime - bTime;
            } else {
              return bTime - aTime;
            }
          }
          // 其它字段按原逻辑
          if (aVal === bVal) return 0;
          if (orderObj.order === 'ascend') {
            return aVal > bVal ? 1 : -1;
          } else {
            return aVal < bVal ? 1 : -1;
          }
        });
      }
    } catch (error) {
      console.error('排序参数解析失败:', error);
    }
  }

  const total = list.length;
  const totalPage = Math.ceil(total / pageSize);
  const startIdx = (page - 1) * pageSize;
  const endIdx = Math.min(startIdx + pageSize, total);
  const pageList = list.slice(startIdx, endIdx);

  return {
    code: '100',
    message: '操作成功',
    data: {
      total,
      pageSize,
      totalPage,
      page,
      startIdx,
      endIdx,
      offset: startIdx,
      list: pageList,
    },
  };
});

// 操作日志-模块下拉列表
Mock.mock('/api/log/getModuleDropdownList', 'post', () => {
  return {
    code: '100',
    message: '操作成功',
    data: moduleList,
  };
});
